
#import "DocumentViewController.h"
#import "CustomNavigationBar.h"
#import "UINavigationItem+Customization.h"
#import "Data.h"
#import "NSString+VoiceOver.h"

@interface DocumentViewController()
@property (nonatomic, strong) UIWebView *currentWebView;
@end

@implementation DocumentViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    CustomNavigationBar *customNavigationBar = (CustomNavigationBar *)self.navigationController.navigationBar;
    
    UIButton* backButton = [customNavigationBar backButtonWith:[UIImage imageNamed:@"btn-back-off.png"] highlight:[UIImage imageNamed:@"btn-back-on.png"] leftCapWidth:14.0 title:self.backButtonTitle];
    backButton.titleLabel.textColor = [UIColor whiteColor];
    backButton.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem customizeTitleInNavigationBarWithHeight:self.navigationController.navigationBar.frame.size.height];
}

-(NSString *)loadDocumentWithName:(NSString *)documentName
{
    NSString *locale = @"sv";
    NSString *file = [locale stringByAppendingFormat:@"_%@", documentName];
    NSLog(@"%@", file);
    NSString *html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] 
                                                         pathForResource:file
                                                         ofType:@"html"] 
                                               encoding:NSUTF8StringEncoding error:nil];
    return [html stringByReplacingOccurrencesOfString:@"../" withString:@""];
}

-(void)showDocumentWithName:(NSString *)documentName
{
    [self showDocumentWithName:documentName andHtml:[self loadDocumentWithName:documentName]];
}

-(void)showDocumentWithName:(NSString *)documentName andHtml:(NSString *)html
{
    [self view]; // Force load of view
    
    if (!documentNames) {
        documentNames = [NSMutableArray array];
        webViews = [NSMutableArray array];
    }
    NSInteger index = [documentNames indexOfObject:documentName];
    UIWebView *currentWebView;
    if (index == NSNotFound) {
        currentWebView = [[UIWebView alloc] initWithFrame:[self getFrameBasedOnScreenSize]];
        currentWebView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
        currentWebView.dataDetectorTypes = UIDataDetectorTypeNone;
        currentWebView.delegate = self;
        
        [documentNames addObject:documentName];
        [webViews addObject:currentWebView];

        [self.view addSubview:currentWebView];
        if (voiceoverEnabled) {
            html = [html stringByOptimizingForVoiceOver];
        }
        [currentWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
        self.currentWebView = currentWebView;
    } else {
        self.currentWebView = webViews[index];
    }
    
    for (UIWebView *webView in webViews) {
        webView.alpha = webView == self.currentWebView ? 1.0 : 0.0;
    }
}

#define kFourInchScreen 568
#define kFrameSizeHeight4Inch 455
#define kFrameSizeHeight3_5Inch 367
- (CGRect)getFrameBasedOnScreenSize
{
    CGRect frame = CGRectZero;
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    if (screenBounds.size.height == kFourInchScreen) {
        // code for 4-inch screen
        frame = self.view.bounds;
        frame.size.height = kFrameSizeHeight4Inch;
    } else {
        // code for 3.5-inch screen
        frame = self.view.bounds;
        frame.size.height = kFrameSizeHeight3_5Inch;
    }
    return frame;
}

- (void)userSwipedRight:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendMailTo:(NSString *)mailTo
{
    NSArray *chunks = [mailTo componentsSeparatedByString:@":"];
    
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    
    NSArray *toRecipients = @[chunks[1]];
    [picker setToRecipients:toRecipients];
    
    [self presentModalViewController:picker animated:YES];
}


#pragma mark - Web view delegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType != UIWebViewNavigationTypeLinkClicked) {
        return YES;
    } else {
        NSString *urlString = [[request URL] absoluteString];
        NSLog(@"urlString: %@", urlString);
        if ([urlString rangeOfString:@"mailto"].location != NSNotFound) {
            [self sendMailTo:urlString];
        } else {
            [[UIApplication sharedApplication] openURL:[request URL]];
        }
        return NO;
    }
}


#pragma mark - Mail composer delegate
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    NSString *message = nil;
    switch (result)
    {
        case MFMailComposeResultSaved:
            message = _(@"Ditt e-postmeddelandet sparat");
            break;
        case MFMailComposeResultSent:
            message = _(@"Ditt e-postmeddelande är skickat");
            break;
        case MFMailComposeResultFailed:
            message = _(@"Misslyckades med att skicka ditt e-postmeddelande");
            break;
        default:
            break;
    }
    
    if (message != nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_(@"Information") message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }

    [self dismissModalViewControllerAnimated:YES];
}

@end
